package cn.uai.activiti8.approval.cmd;

import org.activiti.bpmn.model.EndEvent;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.HistoryService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.util.ProcessDefinitionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * @desc 驳回到当前节点的 上一节点
 * @author uai
 * @since 2025/7/18 23:50
 * @version 1.0
 */
public class Reject2PreNodeCmd extends AbstractRejectCmd<Void> {

    private static final long serialVersionUID = -2349697226844834917L;

    private static final Logger LOGGER = LoggerFactory.getLogger(Reject2PreNodeCmd.class);

    private static final String USER_TASK = "userTask";

    public Reject2PreNodeCmd(String taskId) {
        super(taskId);
    }

    @Override
    protected Void execute(CommandContext commandContext, TaskEntity task) {
        Process process = ProcessDefinitionUtil.getProcess(task.getProcessDefinitionId());
        ExecutionEntity execution = task.getExecution();
        String currentActivityId = execution.getCurrentActivityId();
        LOGGER.info("currentActivityId: {} ", currentActivityId);
        EndEvent endEvent = findEndEvent(process, task.getProcessDefinitionId());
        HistoryService historyService = commandContext.getProcessEngineConfiguration().getHistoryService();
        List<HistoricActivityInstance> userTaskHistoricActivities = historyService.createHistoricActivityInstanceQuery()
                                                                                    .processInstanceId(task.getProcessInstanceId())
                                                                                    .activityType(USER_TASK)
                                                                                    .orderByHistoricActivityInstanceId()
                                                                                    .asc()
                                                                                    .list();


        int prevActivityIndex = getPrevActivityIndex(userTaskHistoricActivities, currentActivityId);
        String pervActivityId = userTaskHistoricActivities.get(prevActivityIndex).getActivityId();
        if (!currentActivityId.equals(pervActivityId)) {
            FlowElement prevUserTask = process.getFlowElement(pervActivityId);
            execution.setCurrentFlowElement(prevUserTask);
        } else {
            execution.setCurrentFlowElement(endEvent);
        }
        execution.setVariable("isPass", false);
        execution.setVariable("actionType", 3);
        // 如果 execution 的 CurrentFlowElement 是一个 UserTask ，
        // planContinueProcessOperation 这种方式会从头开始执行 UserTask 的所有逻辑
        commandContext.getAgenda().planContinueProcessOperation(execution);
        // planTakeOutgoingSequenceFlowsOperation 这种方式会只会寻找 UserTask 的出口，前往下一个节点。
        // commandContext.getAgenda().planTakeOutgoingSequenceFlowsOperation(execution, true);

        // 删除 act_ru_task 中的数据
        task.setExecutionId(null);
        commandContext.getTaskEntityManager().deleteTask(task.getId(), "驳回至上一节点", false);
        // 删除任务还可以用下面这个
        // commandContext.getTaskEntityManager().deleteTask(taskEntity, null, false, false);
        return null;
    }


}
